<template>
	<view>
		<view class="order-food-root">
			  <!-- 顶部轮播图 -->
			      <view class="swiper-wrapper" 
				  :class="{ 'fade-out': !showSwiper, 'fade-in': showSwiper }">
			        <u-swiper
			          :list="swiperList"
			          height="300rpx"
			          indicator
			          circular
			          autoplay
			          indicatorMode="dot"
			        ></u-swiper>
			      </view>
				  <view style="margin-top: 5px;margin-bottom: 6px;">
					  <view style="margin-bottom: 10px;">  
						  <text style="font-size: 26px;">⭐金山大润发店 ></text>
						  <image src="/static/pd.png" style="width: 40px;height: 40px; margin-left: 150px;"></image>
					  </view>
					  <view class="swiper-wrapper"
					  :class="{ 'fade-out': !showSwiper, 'fade-in': showSwiper }">
					    <u-swiper
					      :list="swiperList2"
					      height="100rpx"
					      indicator
					      circular
					      autoplay
					      indicatorMode="dot"
						  img-mode="aspectFill"
					    ></u-swiper>
					  </view>
				  </view>
		  <!-- 上部分：分类 + 内容 -->
		  <view class="content-body u-flex">
		    <!-- 左侧分类导航 -->
		    <scroll-view class="category-nav" 
			  scroll-y 
			  :style="{ height: `calc(100vh - ${swiperHeight}rpx)` }"
			  :scroll-into-view="goToIndex" scroll-with-animation>
		      <view
		        v-for="(item, index) in categories"
		        :key="index"
		        :id="'cat-' + index"
		        :class="['category-item', currentCategory === index ? 'active' : '']"
		        @click="onCategoryClick(index)"
		      >
		        {{ item.name }}
		      </view>
		    </scroll-view>
		
		    <!-- 右侧菜品内容区域 -->
		    <scroll-view
		      class="food-container"
		      scroll-y
				:style="{ height: `calc(100vh - ${swiperHeight}rpx)` }"
		      :scroll-into-view="goToIndex"
		      @scroll="onScroll"
		      scroll-with-animation
		      ref="rightScroll"
				style="padding-bottom:90rpx;"
		    >
		      <view
		        v-for="(item, index) in categories"
		        :key="index"
		        :id="'food-group-' + index"
		        class="food-group"
		        :ref="'foodGroup' + index"
		      >
		        <view class="group-title">{{ item.name }}</view>
		        <view
		          v-for="food in item.foods"
		          :key="food.id"
		          class="food-card u-flex"
		        >
		          <image :src="food.image ? food.image : '/static/default.png'" 
				  class="food-image" 
				  mode="aspectFill" 
				  @click="goToGoodInfo(food.id)"/>
		          <view class="food-info u-flex-col u-flex-1 u-p-l-10" style="margin-left: 0px;">
		            <text class="food-name">{{ food.name }}</text>
		            <text class="food-desc">{{ food.desc }}</text>
		            <text class="food-member">会员下单享9折优惠</text>
		            <text class="food-member">剩余库存：{{ food.stock }}</text>
		            <view class="u-flex u-row-between u-m-t-10">
		              <text class="food-price">￥<text style="font-size: 26px;"> {{ food.price }}</text>
					  <text style="font-size: 22px; color: #999; text-decoration: line-through; margin-left: 10rpx;">
					      ￥{{ food.orderPrice }}
					    </text></text>
		              <view style="margin-left: 115px;margin-top:0px;" v-if="food.count === 0">
							<u-button type="warning" size="mini" style="width: 50rpx; height: 100rpx; font-size: 26px;" @click="onOrderClick(food)">十</u-button>
						</view>
						<view v-else style="display: flex;flex-direction: row;align-items: center;justify-content: center;gap: 20rpx;margin-left: 80rpx;">
						  <u-icon name="minus-circle-fill" color="#fa3534" size="20" @click="onReduceClick(food)" />
						  <text style="margin: 10rpx 10rpx 0rpx 10rpx;">{{ food.count }}</text>
						  <u-icon name="plus-circle-fill" color="#19be6b" size="20" @click="onAddClick(food)" />
						</view>
		            </view>
		          </view>
		        </view>
		      </view>
		    </scroll-view>
		  </view>
		</view>
		
		<!-- 底部悬浮购物车 -->
		<view class="cart-bar">
		  <view class="cart-icon" style="position: relative;width: 40px; height: 40px;" @click="onCartClick">
			  <u-icon name="shopping-cart" size="40" color="#333" />
		    <u-badge :value="cartCount" type="error" absolute :offset="[-10, -10]" >
		    </u-badge>
		  </view>
		  <view style="margin-left: 100px;margin-top: 0px;">
				<u-button type="success" size="small" style="width: 50rpx; height: 130rpx; font-size: 26px;" @click="submitFoods">选好了</u-button>
			</view>
		</view>
		
		<!-- 购物车弹窗 -->
		<u-popup :show="showCartPopup" mode="bottom" @close="showCartPopup = false">
			  <view style="padding: 40rpx; text-align: center;max-height: 90vh;display: flex;flex-direction: column;">
					  <view class="u-text-center u-text-bold u-m-b-20" style="color: red;">
						   <view class="u-text-bold u-text-center" style="flex: 1; color: red;">
						      您的购物车~
						    </view>
						   <view style="width: 50px;margin-left: 350px;">
							   <u-button type="error" size="small" @click="clearCart" style="margin-left: auto;">
							   		清空
							   	</u-button>
						   </view>
				      </view>
				  <view class="u-p-20">
				      <view v-for="(item, index) in cartList" :key="index" class="u-border-bottom u-m-b-20" style="display: flex; flex-direction: row; align-items: flex-start;margin-bottom: 20px;">
				        <!-- 左边：菜品图片 -->
				        <image :src="item.img ? item.img : '/static/default.png'" class="food-image2" mode="aspectFill"/>
				  
				        <!-- 右边内容 -->
				        <view class="u-flex-1 u-m-l-20" style="display: flex; flex-direction: column; justify-content: space-between; height: 160rpx;width: 450rpx; margin-left: 10px;">
				          <view class="u-font-bold" style="text-align: left;font-size: 18px;font-weight: 700;">{{ item.name }}</view>
				          <view class="u-text-sm u-text-gray" style="text-align: left;">{{ item.specText }}</view>
				          <view style="display: flex; justify-content: space-between; align-items: center; margin-top: 10rpx;">
				            <!-- 左边价格 -->
				            <view style="color: red; font-size: 28rpx;">￥{{ item.price.toFixed(2) }}</view>
				          
				            <!-- 右边按钮 -->
				            <view style="display: flex; align-items: center; gap: 20rpx;">
				              <u-icon name="minus-circle-fill" size="25" color="#fa3534" @click="decreaseItem(item)" />
				              <text>{{ item.quantity }}</text>
				              <u-icon name="plus-circle-fill" size="25" color="#19be6b" @click="increaseItem(item)" />
				            </view>
				          </view>

				        </view>
				      </view>
				    </view>
			  </view>
		</u-popup>
	</view>
</template>

<script>
import { getAllDish } from '@/api/orderArtGoods.js';
export default {
  data() {
    return {
      swiperList: [
        '/static/top2.png',
        '/static/top1.png',
        '/static/top3.png',
        '/static/top4.png',
      ],
      swiperList2: [
        '/static/bottom1.png',
        '/static/bottom2.png',
      ],
      categories: [],
      currentCategory: 0,
      goToIndex: '',
      swiperMaxHeight: 300,
      swiperMaxHeight2: 100,
      swiperHeight: 300,
      swiperHeight2: 100,
      scrollTop: 0,
      rightScroll: null,
      foodGroupHeights: [],
	  showSwiper: true, // 用这个控制动画显示
	  isSwiperHidden: false, // 控制节流
      selectedGood: null, //选择的商品
      quantity: 1,
      selectedDish: {},
      showCartPopup: false,
      cartList: [],
      tableNumber: null,
      campusId: null,
      userId: null,
    };
  },
  computed: {
    totalPrice() {
      let base = 0;
      if (this.selectedDish && this.selectedDish.specList) {
        this.selectedDish.specList.forEach(spec => {
          const selectedValue = this.selectedSpecs[spec.name];
          if (selectedValue != null) {
            const option = spec.options.find(opt => opt.value === selectedValue);
            if (option && option.extra) {
              const match = option.extra.match(/[\d.]+/);
              if (match) {
                base += parseFloat(match[0]);
              }
            }
          }
        });
      }
      return (base * this.quantity).toFixed(2);
    },
    cartCount() {
      return this.cartList.reduce((sum, item) => sum + Number(item.quantity || 0), 0);
    },
  },
  methods: {
    getAllGoodList() {
      this.campusId = 1;
	  // uni.setStorageSync('campusId', this.campusId);
      getAllDish(this.campusId).then(res => {
        this.categories = res.data.allGood;
      }).catch(() => {
        uni.showToast({
          type: 'error',
          message: '操作失败，请检查网络',
          duration: 2000
        });
      });
    },
	//清空购物车
    clearCart() {
      this.cartList = [];
      this.syncFoodCount();
	  uni.setStorageSync('cartList', this.cartList);
    },
	//加入购物车和改变购物车数量
	  syncCartWithFood(food) {
		console.log(food,"----242")
	    const existing = this.cartList.find(item => item.id === food.id);
	    if (food.count > 0) {
	      if (existing) {
	        existing.quantity = food.count;
	      } else {
	        this.cartList.push({
	          id: food.id,
	          name: food.name,
	          price: food.price,
			  oldPrice:food.orderPrice,
	          quantity: food.count,
			  img:food.image,
			  specText:food.desc,
			  campusId:this.campusId
	        });
	      }
	    } else {
	      // 移除
	      const index = this.cartList.findIndex(item => item.id === food.id);
	      if (index !== -1) {
	        this.cartList.splice(index, 1);
	      }
	    }
		uni.setStorageSync('cartList', this.cartList); //加入session
	  },
    onOrderClick(food) {
      this.selectedGood = food;
	  food.count = 1;
	  this.syncCartWithFood(food);
      this.quantity = food.count || 1;
    },
    onAddClick(food) {
      this.selectedGood = food;
	   food.count += 1;
	      this.syncCartWithFood(food);
      this.quantity = food.count || 1;
	  
    },
    onReduceClick(food) {
      this.selectedGood = food;
      // this.cartHintText = '您要修改哪些商品?';
      // this.showCartPopup = true;
	  if (food.count > 0) {
	        food.count -= 1;
	        this.syncCartWithFood(food);
	      }
    },
    onCartClick() {
      if (this.cartCount > 0) {
        this.showCartPopup = true;
		console.log(this.cartList,"**-------288")
      } else {
        uni.showToast({
          title: '购物车是空的~',
          icon: 'none'
        });
      }
    },
	//购物车数量减
    decreaseItem(item) {
      item.quantity--;
      if (item.quantity <= 0) {
        const index = this.cartList.indexOf(item);
        if (index !== -1) {
          this.cartList.splice(index, 1);
        }
      }
      this.syncFoodCount();
	   uni.setStorageSync('cartList', this.cartList); //加入session
    },
	//购物车数量加
	increaseItem(item) {
	  item.quantity++;
	  this.syncFoodCount(); // 保证食品列表中对应 count 也同步
	  uni.setStorageSync('cartList', this.cartList);//加入session
	},
	//更新动态
	syncFoodCount() {
	  this.categories.forEach(category => {
	    category.foods.forEach(food => {
	      food.count = this.getCountForFood(food); // 用上上面那个方法
	    });
	  });
	},

	//跳转详情页
	goToGoodInfo(id){
		uni.navigateTo({
		      url: `/pages/goodInfo/goodInfo?id=${id}`
		});
	},
	
    onCategoryClick(index) {
      this.currentCategory = index;
      this.goToIndex = 'food-group-' + index;
    },
    onScroll(e) {
      const scrollY = e.detail.scrollTop;
      
          if (scrollY >= 100 && !this.isSwiperHidden) {
            this.showSwiper = false;
            this.isSwiperHidden = true;
          } else if (scrollY < 100 && this.isSwiperHidden) {
            this.showSwiper = true;
            this.isSwiperHidden = false;
          }
      
          // 分类位置判断逻辑保持不变
          uni.createSelectorQuery()
            .selectAll('.food-group')
            .boundingClientRect(rects => {
              for (let i = 0; i < rects.length; i++) {
                const top = rects[i].top;
                const nextTop = rects[i + 1] ? rects[i + 1].top : Number.MAX_VALUE;
                if (top <= 100 && nextTop > 100) {
                  this.currentCategory = i;
                  break;
                }
              }
            })
            .exec();
    
	},
	
	getCountForFood(food) {
	  const item = this.cartList.find(cartItem => cartItem.id === food.id);
	  return item ? item.quantity : 0;
	},

    submitFoods() {
		if (!this.cartList || this.cartList.length === 0) {
		      uni.showToast({
		        title: '购物车为空，请先添加商品',
		        icon: 'none',
		        duration: 2000
		      });
		      return; // 不跳转
		    }
      uni.navigateTo({
        url: '/pages/confireOrder/confireOrder'
      });
    },
  },
  mounted() {
    this.getAllGoodList();
	uni.$on('clearCartList', () => {
		this.cartList = []  // 更新角标
		uni.removeStorageSync('cartList')
	})
    this.$nextTick(() => {
      let promises = this.categories.map((_, i) => {
        return new Promise(resolve => {
          uni.createSelectorQuery()
            .select(`#food-group-${i}`)
            .boundingClientRect(data => resolve(data ? data.top : 0))
            .exec();
        });
      });
      Promise.all(promises).then(topList => {
        this.foodGroupHeights = topList.map((top, i) => ({
          index: i,
          top
        }));
      });
    });
  },
  
  
};


</script>

<style scoped>
.order-page {
  height: 100vh;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}
.scroll-container {
  height: 100vh;
}
.category-nav {
  width: 160rpx;
  background: #f7f7f7;
  overflow-y: scroll;
    height: 100%;
}

.category-item {
  padding: 20rpx;
  font-size: 28rpx;
  text-align: center;
  color: #666;
}
.category-item.active {
  color: #2979ff;
  font-weight: bold;
  background-color: #fff;
}

.food-container {
  flex: 1;
  height: 100%;
  overflow-y: scroll;
  background: #fff;
  padding: 0 20rpx;
}

.food-group {
  margin-bottom: 40rpx;
}

.group-title {
  font-size: 32rpx;
  font-weight: bold;
  margin: 20rpx 0;
}

.food-card {
  display: flex;
  flex-direction: row;
  background-color: #f9f9f9;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  width: 500rpx;
}

.food-info{
	flex:1;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
}


.food-image {
  width: 160rpx;
  height: 160rpx;
  margin-right: 20rpx;
  flex-shrink: 0;
  /* border-radius: 12rpx; */
}
.food-image2 {
  width: 160rpx;
  height: 160rpx;
  display: block;
  border-radius: 8rpx;
}
.food-name {
  font-size: 30rpx;
  font-weight: bold;
}
.food-desc {
  font-size: 24rpx;
  color: #888;
  margin-top: 8rpx;
}
.food-member {
  font-size: 22rpx;
  color: #f56c6c;
  margin-top: 8rpx;
}
.food-price {
  font-size: 30rpx;
  color: red;
}



.cart-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.1);
  padding: 0 30rpx;
  z-index: 999;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.cart-icon {
  position: relative; /* 确保 u-badge 的 absolute 定位基于此容器 */
}

.spec-option {
  padding: 10rpx 20rpx;
  margin: 0 10rpx 10rpx 0;
  border: 1px solid #ccc;
  border-radius: 30rpx;
  font-size: 26rpx;
  background-color: #f8f8f8;
}
.spec-option.selected {
  border-color: #f56c6c;
  background-color: #fef0f0;
  color: #f56c6c;
}
.cart-popup {
  padding: 20rpx;
  box-sizing: border-box;
  background-color: #fff;
}

.cart-title {
  font-size: 34rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.cart-item {
  display: flex;
  margin-bottom: 20rpx;
  background-color: #f8f8f8;
  border-radius: 16rpx;
  padding: 20rpx;
}

.dish-img {
  width: 140rpx;
  height: 140rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
}

.dish-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.dish-name {
  font-size: 30rpx;
  font-weight: 500;
}

.dish-spec {
  font-size: 26rpx;
  color: #999;
}

.dish-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dish-price {
  font-size: 30rpx;
  color: #e64340;
  font-weight: bold;
}

.dish-step {
  display: flex;
  align-items: center;
}

.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0 0;
  border-top: 1px solid #eee;
}
.total-price {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}

.swiper-wrapper {
  width: 100%;
/*  height: 300rpx;
  margin-bottom: 20rpx; */
}
.content-body {
   display: flex;
    flex: 1;
    overflow: hidden;
}
.fade-in {
  opacity: 1;
  height: auto;
  transition: opacity 0.3s ease, height 0.3s ease;
}
.fade-out {
  opacity: 0;
  height: 0 !important;
  overflow: hidden;
  transition: opacity 0.3s ease, height 0.3s ease;
}
</style>
